from flask_restful import Resource, reqparse
from flask import request
from models import db, ShoppingCart
from utils import api_response

class CartList(Resource):
    def get(self):
        """获取购物车列表"""
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', type=int, location='args')
        parser.add_argument('page', type=int, default=1, location='args')
        parser.add_argument('size', type=int, default=10, location='args')
        args = parser.parse_args()
        
        query = ShoppingCart.query
        if args['user_id'] is not None:
            query = query.filter_by(user_id=args['user_id'])
        
        carts = query.paginate(
            page=args['page'], 
            per_page=args['size'], 
            error_out=False
        )
        
        return api_response({
            'total': carts.total,
            'page': args['page'],
            'size': args['size'],
            'carts': [cart.to_dict() for cart in carts.items]
        })
    
    def post(self):
        """添加购物车项"""
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', type=int, required=True, help='用户ID不能为空')
        parser.add_argument('dish_id', type=int, required=True, help='菜品ID不能为空')
        parser.add_argument('quantity', type=int, default=1)
        parser.add_argument('remarks', type=str)
        parser.add_argument('meal_type', type=str, required=True, help='餐次类型不能为空')
        args = parser.parse_args()
        
        # 检查是否已存在相同的购物车项
        existing_cart = ShoppingCart.query.filter_by(
            user_id=args['user_id'],
            dish_id=args['dish_id'],
            meal_type=args['meal_type']
        ).first()
        
        if existing_cart:
            # 如果已存在，更新数量
            existing_cart.quantity += args['quantity']
            if args['remarks']:
                existing_cart.remarks = args['remarks']
            cart = existing_cart
        else:
            # 如果不存在，创建新的购物车项
            cart = ShoppingCart(
                user_id=args['user_id'],
                dish_id=args['dish_id'],
                quantity=args['quantity'],
                remarks=args['remarks'],
                meal_type=args['meal_type']
            )
            db.session.add(cart)
        
        db.session.commit()
        
        return api_response(cart.to_dict(), message='购物车项添加成功')

class CartDetail(Resource):
    def get(self, cart_id):
        """获取购物车项详情"""
        cart = ShoppingCart.query.get(cart_id)
        if not cart:
            return api_response({'message': '购物车项不存在'}, code=404)
        
        return api_response(cart.to_dict())
    
    def put(self, cart_id):
        """更新购物车项"""
        cart = ShoppingCart.query.get(cart_id)
        if not cart:
            return api_response({'message': '购物车项不存在'}, code=404)
        
        parser = reqparse.RequestParser()
        parser.add_argument('quantity', type=int)
        parser.add_argument('remarks', type=str)
        args = parser.parse_args()
        
        if args['quantity'] is not None:
            cart.quantity = args['quantity']
        if args['remarks'] is not None:
            cart.remarks = args['remarks']
        
        db.session.commit()
        
        return api_response(cart.to_dict(), message='购物车项更新成功')
    
    def delete(self, cart_id):
        """删除购物车项"""
        cart = ShoppingCart.query.get(cart_id)
        if not cart:
            return api_response({'message': '购物车项不存在'}, code=404)
        
        db.session.delete(cart)
        db.session.commit()
        
        return api_response(None, message='购物车项删除成功')